import {createDefaultAction, createSubFormAction} from '@/components/hhd/design/FormDesigner/types';

export default class ActionUtils {
  refreshActions(actions, formDefinition) {
    if (!actions || !actions.length) {
      this.createDefaultActions(actions, formDefinition);
    } else {
      this.patchActions(actions, formDefinition);
    }
  }

  patchActions(actions, formDefinition) {
    actions = actions || [];
    actions.forEach(action => {
      let fieldActions = action.fieldActions || [];
      let tempAction = createDefaultAction(formDefinition, action.actionName, action.actionType, action.system);
      let tempFieldActions = tempAction.fieldActions || [];
      for (let i = 0; i < tempFieldActions.length; i++) {
        let tempFieldAction = tempFieldActions[i];
        let index = fieldActions.findIndex(f => f.fieldId === tempFieldAction.fieldId);
        if (index !== -1) {
          tempFieldActions[i] = fieldActions[index];
        }
      }
      action.fieldActions = tempFieldActions;

      let tempSubFormActions = createSubFormAction(formDefinition, action.actionType)
      let subFormActions = action.subFormActions || []
      for (let i = 0; i < tempSubFormActions.length; i++) {
        let index = subFormActions.findIndex(s => s.subFormId === tempSubFormActions[i].subFormId);
        if (index !== -1) {
          tempSubFormActions[i] = subFormActions[index];
        }
      }
      action.subFormActions = tempSubFormActions;
    });
  }

  createDefaultActions(actions, formDefinition) {
    actions.push(createDefaultAction(formDefinition, '填写', 'add', true));
    actions.push(createDefaultAction(formDefinition, '审批', 'edit', true));
    actions.push(createDefaultAction(formDefinition, '显示', 'detail', true));
  }
}